﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MineLaunch.Controls
{
	public class DragDropListBoxItem : ListBoxItem
	{
		static DragDropListBoxItem()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(DragDropListBoxItem),
				new FrameworkPropertyMetadata(typeof(ListBoxItem)));
		}

		public ListBoxItem dragItem;
		public Point dragStartPosition;
		public DragDropAdorner dragGhost;

		public DragDropListBox parentListBox;

		protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
		{
			dragItem = e.Source as DragDropListBoxItem;
			dragStartPosition = e.GetPosition(dragItem);
		}

		protected override void OnPreviewMouseMove(MouseEventArgs e)
		{
			if (!this.parentListBox.AllowDrop) return;
			var listboxitem = e.Source as ListBoxItem;
			if (e.LeftButton == MouseButtonState.Pressed && dragGhost == null && dragItem == listboxitem && parentListBox != null)
			{
				var nowPos = e.GetPosition(listboxitem);
				if (Math.Abs(nowPos.X - dragStartPosition.X) > SystemParameters.MinimumHorizontalDragDistance ||
					Math.Abs(nowPos.Y - dragStartPosition.Y) > SystemParameters.MinimumVerticalDragDistance)
				{
					var layer = AdornerLayer.GetAdornerLayer(parentListBox);
					dragGhost = new DragDropAdorner(parentListBox, listboxitem, 0.5, dragStartPosition);
					layer.Add(dragGhost);
					DragDrop.DoDragDrop(listboxitem, listboxitem, DragDropEffects.Move);
					layer.Remove(dragGhost);
					dragGhost = null;
					dragItem = null;
				}
			}
		}

		protected override void OnQueryContinueDrag(QueryContinueDragEventArgs e)
		{
			if (dragGhost != null && parentListBox != null)
			{
				var p = Common.Common.GetMousePosition(parentListBox);
				var loc = (Window.GetWindow(this)).PointFromScreen(parentListBox.PointToScreen(new Point(0, 0)));
				dragGhost.LeftOffset = p.X - loc.X;
				dragGhost.TopOffset = p.Y - loc.Y;
			}
		}

		protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
		{
			base.OnMouseDoubleClick(e);
			DragDropItem item = parentListBox.SelectedItem as DragDropItem;
			if (item == null) return;
			item.DragDropListBoxItem_MouseDoubleClick(this, e);
		}
	}
}
